package top.kaoshanji.p1ch05a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.p1ch04a.Dish;
import top.kaoshanji.p1ch04a.Type;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/11 9:41
 */
public class Filtering {

    private static final Logger logger = LogManager.getLogger(Filtering.class);

    public static void main(String[] args) {

        // 代码清单-p1ch05a-87页a：用谓词筛选
        logger.info("...用谓词筛选...");
        List<Dish> vegetarianMenu = Dish.menu.stream()
                .filter(Dish::isVegetarian)
                .collect(Collectors.toList());
        vegetarianMenu.forEach(System.out::println);


        // 代码清单-p1ch05a-87页b：筛选各异的元素
        logger.info("...筛选各异的元素...");
        List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
        numbers.stream()
                .filter(i -> i % 2 == 0)
                .distinct()
                .forEach(System.out::println);


        List<Dish> specialMenu = Arrays.asList(
                new Dish("season fruit", true, 120, Type.OTHER),
                new Dish("prawns", false, 300, Type.FISH),
                new Dish("rice", true, 350, Type.OTHER),
                new Dish("chicken", false, 400, Type.MEAT),
                new Dish("french fries", true, 530, Type.OTHER));

        // 代码清单-p1ch05a-89页a：使用学习过的filter操作
        logger.info("...使用学习过的filter操作...");
        List<Dish> filteredMenu = specialMenu.stream()
                .filter(dish -> dish.getCalories() < 320)
                .collect(Collectors.toList());
        filteredMenu.forEach(System.out::println);


        // 代码清单-p1ch05a-89页b：使用takeWhile
        logger.info("...使用takeWhile...");
        List<Dish> slicedMenu1 = specialMenu.stream()
                .takeWhile(dish -> dish.getCalories() < 320)
                .collect(Collectors.toList());
        slicedMenu1.forEach(System.out::println);


        // 代码清单-p1ch05a-89页c：使用dropWhile
        logger.info("...使用dropWhile...");
        List<Dish> slicedMenu2 = specialMenu.stream()
                .dropWhile(dish -> dish.getCalories() < 320)
                .collect(Collectors.toList());
        slicedMenu2.forEach(System.out::println);


        // 代码清单-p1ch05a-90页a：截短流
        logger.info("...截短流...");
        List<Dish> dishesLimit3 = Dish.menu.stream()
                .filter(d -> d.getCalories() > 300)
                .limit(3)
                .collect(Collectors.toList());
        dishesLimit3.forEach(System.out::println);


        // 代码清单-p1ch05a-90页b：跳过元素
        logger.info("...跳过元素...");
        List<Dish> dishesSkip2 = Dish.menu.stream()
                .filter(d -> d.getCalories() > 300)
                .skip(2)
                .collect(Collectors.toList());
        dishesSkip2.forEach(System.out::println);


    }

}
